<template>
  <div>
    <el-form ref="bill" class="bill" :model="bill" :rules="rules">
      <el-row :gutter="6">
        <el-col :span="6">
          <el-form-item prop="distributorFk" label="供应商编号：">
            <!--            <el-input v-model.trim="bill.distributorFk"></el-input>-->
            <el-autocomplete
              v-model.trim="bill.distributorFk"
              :fetch-suggestions="fetchDistributor"
              @select="chooseDistributor"
            >
              <template slot-scope="which">
                <span>{{
                  which.item.companyName + " ," + which.item.distributorCode
                }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item prop="distributorName" label="供应商名称：">
            <el-autocomplete
              v-model="bill.distributorName"
              :fetch-suggestions="fetchDistributor"
              @select="choose"
            >
              <template slot-scope="which">
                <span>{{
                  which.item.companyName + " ," + which.item.distributorCode
                }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-button type="primary" icon="el-icon-edit" @click="addBatchItem()"
          >添加采购商品
        </el-button>
      </el-row>
      <el-row>
        <el-table :data="bill.commodityBatches" stripe>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="商品名称" align="center">
            <template slot-scope="that">
              <el-form-item>
                <!--                <el-input v-model="that.row.commodityDescr"></el-input>-->
                <!--                注意下面@select函数已经被autoComplete标签规定了入参只能有一个item-->
                <!--                那么作用域插槽带来的that引用，如果写在下面的方法区中，将无法传递that引用。-->
                <!--
                    @select="
                    (item) => {
                      that.row.commodityDescr = item.commodityDescr;
                      that.row.commodityFk = item.commodityCode;
                    }
                  "-->
                <el-autocomplete
                  v-model="that.row.commodityDescr"
                  :fetch-suggestions="fetchCommodity"
                  @focus="currentBatch = that.row"
                  @select="chooseCommodity"
                >
                  <template slot-scope="which">
                    <span>{{
                      which.item.commodityDescr + ":" + which.item.commodityCode
                    }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="商品编号" align="center">
            <template slot-scope="that">
              <el-form-item>
                <!--                <el-input v-model="that.row.commodityFk"></el-input>-->
                <el-autocomplete
                  v-model="that.row.commodityFk"
                  :fetch-suggestions="fetchCommodity"
                  @focus="currentBatch = that.row"
                  @select="chooseCommodity"
                >
                  <template slot-scope="which">
                    <span>{{
                      which.item.commodityCode + ":" + which.item.commodityDescr
                    }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </template>
          </el-table-column>
          <!--   purchasePrice: 0,
            advanceQuantity: null,
            unit: null,-->
          <el-table-column label="采购单价" align="center" width="100">
            <template slot-scope="that">
              <el-form-item>
                <el-input
                  v-model="that.row.purchasePrice"
                  @blur="calculateTotalPrice"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="采购单位" align="center" width="80">
            <template slot-scope="that">
              <el-form-item>
                <el-select v-model="that.row.unit">
                  <el-option
                    v-for="u in units"
                    :key="u"
                    :value="u"
                    :label="u"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" align="center" width="80">
            <template slot-scope="that">
              <el-form-item>
                <el-input
                  v-model.number="that.row.advanceQuantity"
                  @blur="calculateTotalPrice"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!--     expirationStart: null,
            expirationStop: null,
          -->
          <el-table-column label="生产日期" align="center">
            <template slot-scope="that">
              <el-form-item>
                <el-date-picker
                  v-model="that.row.expirationStart"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="保质期到" align="center">
            <template slot-scope="that">
              <el-form-item>
                <el-date-picker
                  v-model="that.row.expirationStop"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column width="180px" fixed="left">
            <template slot-scope="that">
              <el-button
                class="el-button--mini"
                type="warning"
                icon="el-icon-edit"
                @click="openById(that.row.commodityFk)"
                >编辑</el-button
              >
              <el-button
                class="el-button--mini"
                type="danger"
                icon="el-icon-edit"
                @click="deleteById(that.row.commodityFk)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <el-row :gutter="6">
        <el-col :span="6">
          <el-form-item prop="ultraCharge" label="本次采购额外经费：">
            <el-input v-model.number="bill.ultraCharge"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item prop="advanceCharge" label="采购单支出小计：">
            <el-input disabled v-model.number="bill.advanceCharge"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" icon="el-icon-edit" @click="billSubmit()"
          >提交
        </el-button>
        <el-button
          type="warning"
          icon="el-icon-remove"
          @click="() => $refs.bill.resetFields()"
          >重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import New from './components/New.vue';
import { billModuleApi, commodityModuleApi } from "@/api/apis";
const units = ["包", "箱", "盒", "个", "根"];
export default {
  name: "PurchaseStockInBill",
  components: {
    // New,Old,
  },
  props: {
    sampleP: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      units: units,
      sampleD: "value",
      //标准业务单据结构
      batchOperating: {},
      bill: {
        distributorFk: "SS47485070000001",
        distributorName: "山东麒麟综合贸易商城",
        ultraCharge: 0,
        //意向付款 ×
        advanceCharge: null,

        actualCharge: null,
        //本次采购的店长评价
        billRemark: null,
        //采购单创建时间
        createTime: null,
        deliver: null,
        deliverPhone: null,
        deliverTime: null,
        examiner: null,
        isDeleted: false,
        planner: null,
        purchaseBillCode: null,
        purchaseBillId: 0,
        purchaseBillState: "notReceive",
        updateTime: null,
        // version: 0,
        commodityBatches: [
          {
            commodityDescr: null,
            commodityFk: null,
            purchasePrice: null,
            advanceQuantity: null,
            unit: null,
            expirationStart: null,
            expirationStop: null,

            actualQuantity: null,
            batchCode: null,
            batchId: 0,
            isDeleted: false,
            purchaseBillFk: null,
            remainingQuantity: null,
            version: 0,
          },
        ],
      },
      rules: {},
      //代表用户当前操作的条目 也就是table标签作用域插槽里的that.row
      currentBatch: {},
    };
  },
  computed: {
    // sampleC() {
    //     return this.sampleD+'--';
    // }
  },
  created() {},
  mounted() {
    while (this.bill.commodityBatches.length < 5) {
      this.addBatchItem();
    }
  },
  methods: {
    sampleM() {},
    billSubmit() {
      this.$message.success(JSON.stringify(this.bill));

      // this.$http({
      //   method: "post",
      //   url: "/bill/purchase/insert",
      //   data: this.bill,
      // })
      billModuleApi.purchaseInsertApi(this.bill).then(
        (res) => {
          this.$message.warning(JSON.stringify(res.data));
        },
        (error) => {
          console.log("bill request error : " + error.response.status);
        }
      );
    },
    addBatchItem() {
      this.bill.commodityBatches.push({
        commodityDescr: null,
        commodityFk: null,
        purchasePrice: null,
        advanceQuantity: null,
        unit: null,
        expirationStart: null,
        expirationStop: null,

        actualQuantity: null,
        batchCode: null,
        batchId: 0,
        isDeleted: false,
        purchaseBillFk: null,
        remainingQuantity: null,
        version: 0,
      });
    },
    deleteById(cmFk) {
      let k = this.bill.commodityBatches;
      k.splice(
        k.findIndex((x) => x.commodityFk === cmFk),
        1
      );
    },
    calculateTotalPrice() {
      let sum = 0;
      for (let e of this.bill.commodityBatches) {
        if (e.purchasePrice && e.advanceQuantity) {
          // console.log(e.purchasePrice,e.advanceQuantity);
          sum += e.purchasePrice * e.advanceQuantity;
        }
      }
      // console.log("总计费用"+sum);
      this.bill.advanceCharge = sum;
    },
    fetchDistributor(queryString, cb) {
      // this.$notify.success("将要依据用户输入查询：" + queryString);

      /** res data 结构
       *  {
    "distributorId": 2,
    "distributorCode": "SS47775175000002",
    "companyName": "山西壶化集团股份有限公司",
    "companyAddress": "山西省太原市迎宾大道255号",
    "phoneNumber": "15589896363",
    "creditLevel": 0,
    "supplyDescr": "经营酒类,日常食品,油粮",
    "isDeleted": false
        },
      *
      * */
      /*  this.$http({
              method: "post",
              url: "/",
              data: this.queryString,
            })*/
      commodityModuleApi.distributorFindApi(queryString).then(
        (res) => {
          // this.$message.warning(JSON.stringify(res.data));
          cb(res.data);
        },
        (error) => {
          console.log(".queryString request error : " + error.response.status);
          cb([]);
        }
      );
    },
    chooseDistributor(item) {
      this.bill.distributorFk = item.distributorCode;
      this.bill.distributorName = item.companyName;

    },
    fetchCommodity(queryString, callback) {
      /** res data [] struct
      * {
    "commodityId": 6,
    "commodityCode": "CC47235225000216",
    "commodityDescr": "君乐巧克力纯牛奶",
    "barCode": "11112277",
    "specification": "250ml",
    "retailPrice": 3.25,
    "chargeUnit": "盒",
    "producingArea": "内蒙古第八旗",
    "qualityLevel": 1,
    "typeFk": 7,
    "isDeleted": false
  }
      * */
      // this.$http({
      //         method: "get",
      //         url: "/commodity/commodityEntity/find",
      //       })
      commodityModuleApi.cmEntityFindApi(queryString).then(
        (res) => {
          // this.$message.warning(JSON.stringify(res.data));
          callback(res.data);
        },
        (error) => {
          console.log(" request error : " + error.response.status);
          callback([]);
        }
      );
    },
    chooseCommodity(item) {
      this.currentBatch.commodityDescr = item.commodityDescr;
      this.currentBatch.commodityFk = item.commodityCode;
      this.$message.success("参考信息：当前商品的统一零售价为"
              +item.retailPrice+"元/"+item.specification)
    },
  },
  watch: {
    // sampleC(newValue, oldValue) {
    //
    // }
  },
};
</script>

<!--<style scoped>-->
<style lang="scss" scoped></style>
